// TestClient.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <conio.h>
#include "msgLoginServer.h"

void ProcessCommand( xgc_char szCommand[] );
void ProcessPacket( net::INetPacket* pPacket );

int _tmain(xgc_int32 argc, xgc_tchar argv[])
{
	net::CreateNetwork( net::asio );
	net::InitNetwork( 10 );

	ASSERT( argc >= 3 );
	net::IMessageQueue *mQueue = xgc_nullptr;
	net::AsyncConnectServer( argv[1], _ttoi(argv[2]), net::ProtocalDefault, &mQueue, 0, 0 );
	do
	{
		mQueue->AddRef();
		if( _kbhit() )
		{
			char ch = _getch();
			switch( ch )
			{
			case 13:
				{
					char szBuffer[1024*4];
					DWORD dwRead = 0;
					printf( ">" );
					if( ReadConsole( GetStdHandle(STD_INPUT_HANDLE), szBuffer, sizeof(szBuffer), &dwRead, NULL ) != 0 )
					{
						szBuffer[dwRead] = 0;
						ProcessCommand( szBuffer );
					}
				}
				break;
			case 27:
				mQueue->Release();
				break;
			}
		}

		ProcessPacket( mQueue->PopMessage() );
	}while( mQueue->Release() );
	net::FiniNetwork();
	net::DestroyNetwork();
	return 0;
}

xgc_void ProcessHelp( xgc_lpstr cmdline )
{

}

static char splite[] = "\xd\xa ,/-";

xgc_void ProcessLogin( xgc_lpstr cmdline )
{
	msgLoginRequest req;

	req.username = strtok_s( NULL, splite, &cmdline );
	req.password = strtok_s( NULL, splite, &cmdline );
	xgc_size packet_size = MAX_PACKET_SIZE;
	xgc_lpstr packet = (xgc_lpstr)net::AllocPacket( packet_size );
	serialization serialize( packet, packet_size );

	serialize << req;
	net::SendPacket( 0, serialize.base(), serialize.wd() );
}

void ProcessCommand( xgc_char szCommand[] )
{
	typedef xgc_void (*func)( xgc_lpstr cmdline );
	struct 
	{
		xgc_lpcstr cmd;
		func fn;
	}
	command[] =
	{
		{ "help", ProcessHelp },
		{ "login", ProcessLogin },
	};

	xgc_lpstr tok = xgc_nullptr;
	xgc_lpstr str = strtok_s( szCommand, splite, &tok );
	if( str )
	{
		for( int i = 0; i < _countof(command); ++i )
		{
			if( stricmp( command[i].cmd, str ) == 0 )
				command[i].fn( tok );
		}
	}
}

void ProcessPacket( net::INetPacket* pPacket )
{
}